<!-- 2024/11/15生产管理-生产工单-生产退料按钮 弹框 -->
<template>
  <el-dialog :title="title" :visible.sync="open" width="90%" append-to-body @close="cancel">
    <div>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-tag size="large" style="font-size: 20px;">基本信息</el-tag>
        <hr />
        <el-row>
          <el-col :span="8">
            <el-form-item label="退料编码" prop="backCode">
              <div style="display: flex;">
                <el-input v-model="form.backCode" placeholder="请输入退料编码" v-if="optType === 'add'" style="flex:1;" />
                <span v-if="optType === 'update' || optType === 'check'">{{ form.backCode }}</span>
                <el-switch v-model="autoGenFlag" active-color="#13ce66" active-text="自动生成" @change="handleAutoGenChange(autoGenFlag)" v-if="optType !== 'update' && optType !== 'check'"></el-switch>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="生产工单id" prop="workorderId">
              <el-input v-model="form.workorderId" placeholder="请输入生产工单id" v-if="optType !== 'check'" disabled style="width: 220px;" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="生产工单" prop="workorderCode">
              <el-input v-model="form.workorderCode" disabled style="width: 220px;" />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <!-- 2024-11-20 新增退料类型：原料退料、半成品退料。根据选项控制下方表单字段显隐，原料退料显示 物料选择框，半成品退料显示 扫码输入框 -->
            <el-form-item label="退料类型" prop="backType">
              <el-select style="width: 220px;" v-model="form.backType" placeholder="请选择退料类型">
                <el-option v-for="(item, index) of dict.type.mes_material_back_type" :key="index" :label="item.label" :value="item.value">{{ item.label }}</el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="退料原因" prop="reasonVal">
              <el-select style="width: 220px;" clearable v-model="form.reasonVal" placeholder="请选择退料原因" v-if="optType !== 'check'" @change="changeReasonVal">
                <el-option v-for="(item, index) of dictList" :key="index" :label="item.dictLabel" :value="item.dictValue">{{ item.dictLabel }}</el-option>
              </el-select>
              <span v-if="optType === 'check'">
                <dict-tag :options="dict.type.mes_material_back_reason" :value="form.reasonVal" />
              </span>
            </el-form-item>
          </el-col>
          <!-- 2024-12-20 djj 新增仓库、库位查询条件 -->
          <el-col :span="8">
            <el-form-item label="仓库" prop="warehouseId">
              <el-select v-model="form.warehouseId" placeholder="请选中仓库" clearable filterable @change="changeWarehouse">
                <el-option v-for="item in warehouseList" :key="item.warehouseId" :label="item.warehouseName" :value="item.warehouseId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="扫SN码" prop="materialSerial" v-if="form.backType == '2'">
              <!-- <el-input v-model="form.materialSerial" placeholder="扫SN码" style="width: 220px;"
                :disabled="optType == 'check'" @keyup.enter.native="querySnCodeInfo" /> -->
              <el-input type="textarea" :rows="6" v-model="form.materialSerial" placeholder="扫SN码" style="width: 220px;" :disabled="optType == 'check'" @keyup.enter.native="querySnCodeInfo" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="物料" prop="material" v-if="form.backType == '1'">
              <el-select v-model="form.material" filterable placeholder="请选择物料" clearable @change="changeMaterial">
                <el-option v-for="item in materialList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>

          <!--  <el-col :span="8">
                        <el-form-item label="库位" prop="areaId">
                            <el-select v-model="form.areaId" placeholder="请选中库位" clearable filterable
                                @change="changeArea">
                                <el-option v-for="item in areaList" :key="item.areaId"
                                    :label="item.areaCode + '[' + item.attr3 + ']'" :value="item.areaId" />
                            </el-select>
                        </el-form-item>
                    </el-col> -->

          <!-- <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" placeholder="请输入备注" v-if="optType!=='check'" />
            <span v-if="optType==='check'">{{form.remark}}</span>
          </el-form-item> -->
          <!-- <el-col :span="12">
              <el-form-item label="仓库信息" prop="warehouseId">
                <el-select
                  clearable
                  v-model="form.warehouseId"
                  placeholder="请选择仓库信息"
                  v-if="optType!=='check'"
                >
                  <el-option
                    v-for="(item,index) of warehouseList"
                    :key="index"
                    :label="item.warehouseName"
                    :value="item.warehouseId"
                  >{{item.warehouseName}}</el-option>
                </el-select>
                <span v-if="optType==='check'">{{form.warehouseName}}</span>
              </el-form-item>
            </el-col> -->
        </el-row>
      </el-form>
    </div>
    <div v-if="personList.length > 0">
      <el-tag size="large" style="font-size: 20px;">审批流信息</el-tag>
      <hr />
    </div>
    <div>
      <el-steps :active="stepResult == 'REFUSE' ? activeStep : activeStep" align-center>
        <el-step v-for="item in personList" :key="item.userMobile" :title="item.userNickname" :description="item.resultName" :status="item.result == 'REFUSE' ? 'error' : ''"></el-step>
      </el-steps>
    </div>
    <div>
      <el-tag size="large" style="font-size: 20px;">物料信息</el-tag>
    </div>
    <hr />
    <!-- <el-tabs type="border-card" >
        <el-tab-pane label="详情">-->
    <back-detail ref="backDetail" @onSelected="onSelected" :optType="optType" :parentCode="parentCode" :parentId="parentId"></back-detail>
    <!-- </el-tab-pane>
        </el-tabs>-->

    <div slot="footer" class="dialog-footer" v-if="optType !== 'check'">
      <el-button type="primary" @click="submitForm" :disabled="disabledSubmit">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import BackDetail from './backDetail.vue';
import { genCode } from "@/api/mes/md/rule";
import {
  listBack,
  getBack,
  delBack,
  addBatchBackInfo,
  updateBatchBackInfo,
  getBackResonList,
  backProcess,
  getBackCreateProcess,
  backGenerate,
  getSequenceCodeByWorkorderCode,
  getItemList, getListByScanning
} from "@/api/mes/pro/productBack";
import { listWarehouse } from "@/api/mes/wm/warehouse";
import { listArea } from "@/api/mes/wm/area"
import { onMounted } from 'vue-demi';
export default {
  dicts: ["mes_material_back_reason", "mes_material_back_type"],
  components: { BackDetail },
  data() {
    return {
      title: "生产退料",
      open: false,
      disabledSubmit: false,
      // 表单参数
      form: {
        backCode: '',
        backType: '1',
        warehouseId: null,
        warehouseCode: null,
        warehouseName: null,
        areaId: null,
        areaCode: null,
        areaName: null,
      },
      // 表单校验
      rules: {
        backCode: { required: true, message: '请输入退料编码', trigger: 'blur' },
        reasonVal: { required: true, message: '请选择退料原因', trigger: 'change' },
        warehouseId: { required: true, message: '请选择仓库', trigger: 'change' },
      },
      optType: null,
      parentCode: "",
      selectedRows: null,
      autoGenFlag: false,
      parentId: "",
      //审批人
      personList: [],
      //处于哪个环节
      activeStep: null,
      stepResult: null,
      dictList: [],
      checkType: null,
      openPrint: false,
      snList: [],
      selectSequenceCode: null,
      materialList: [],//2024-11-18 可退料物料
      addBackMaterialList: [],//新增退货物料列表
      // 库存记录表格数据
      warehouseList: [],
      areaList: [],
    };
  },
  watch: {
    selectedRows: {
      // 每个属性值发生变化就会调用这个函数
      handler(newVal, oldVal) {
        console.log('oldVal-selectedRows:', oldVal)
        console.log('newVal-selectedRows:', newVal)
        this.snList = this.snList.filter(item => {
          return !(newVal.some(element => element.materialSerial === item.sequenceCode))
        })
      },
      // 立即处理 进入页面就触发
      immediate: true,
    },
  },
  methods: {
    //初始化函数
    init(row) {
      this.form = { ...this.form, ...row };
      this.open = true;
      this.optType = "add";
      this.getDictList();
      this.handleWorkorderId();/* 查询可以退的物料列表 */
      this.getWarehouseList();
    },
    /* 2024-12-20 djj 新增仓库、库位查询条件 start*/
    /* 选择仓库 */
    changeWarehouse(val) {
      this.form.areaId = null;
      if (val) {
        //  选中的数据和options进行匹配
        var item = {}
        item = this.warehouseList.find(function (i) { return i.warehouseId === val });
        this.form.warehouseId = item.warehouseId
        this.form.warehouseCode = item.warehouseCode
        this.form.warehouseName = item.warehouseName
        this.getAreaList();
      }
    },
    /* 选择库位 */
    changeArea(val) {
      if (val) {
        //  选中的数据和options进行匹配
        var item = {}
        item = this.areaList.find(function (i) { return i.areaId === val });
        this.form.areaId = item.areaId
        this.form.areaCode = item.areaCode
        this.form.areaName = item.areaName
      }
    },
    /* 获取仓库信息 */
    getWarehouseList() {
      listWarehouse({ pageSize: 999 }).then(response => {
        this.warehouseList = response.rows || []
      }).catch(() => {
        this.warehouseList = []
      })
    },
    /* 获取库位信息 */
    getAreaList() {
      if (!this.form.warehouseId) { return this.areaList = [] }
      listArea({ wareHouseId: this.form.warehouseId }, { "no-page": true }).then(response => {
        this.areaList = response.rows || []
      }).catch(() => {
        this.areaList = []
      })
    },
    /* 2024-12-20 djj 新增仓库、库位查询条件 end */
    /* 获取退料原因 */
    getDictList() {
      getBackResonList().then(response => {
        this.dictList = response.data;
        // this.dictList.forEach((val, key) => {
        //   val.dictValue = Number(val.dictValue);
        // });
      });
    },
    querySearch(queryString, cb) {
      this.handleGetSN(cb, queryString)
    },
    createStateFilter(queryString) {
      return (state) => {
        return state.sequenceCode.includes(queryString);
      };
    },
    handleSelect(item) {
      this.selectSequenceCode = item.sequenceCode
      console.log(111, item)
    },
    handleGetSN() {
      getSequenceCodeByWorkorderCode(this.form.workorderId).then(res => {
        console.log(res)
        this.form.workorderCode = res.data.workorderCode
        const arr = res.data.sequenceCode ? res.data.sequenceCode : []
        const newArr = arr.map(item => {
          const obj = {
            sequenceCode: item
          }
          return obj
        })
        this.snList = newArr.filter(item => {
          if (this.selectedRows) {
            return !(this.selectedRows.some(element => element.materialSerial === item.sequenceCode))
          } else {
            return true;
          }

        })
        if (cb) {
          var snList = this.snList;
          var results = queryString ? snList.filter(this.createStateFilter(queryString)) : snList;
          cb(results);
        }
      })
    },
    onSelected(selectedRows) {
      this.selectedRows = selectedRows;
    },
    /* 2024-11-18 djj 查询可以退的物料列表 */
    handleWorkorderId() {
      let newArr = []
      let obj = {}
      if (!this.form.workorderId) return
      getItemList(this.form.workorderId).then(res => {
        const arr = res.data ? res.data : []
        newArr = arr.map(item => {
          obj = {
            'value': item.itemCode,
            'label': item.itemCode + '/' + item.itemName + '/' + item.specification,
            ...item
          }
          return obj
        })
        this.materialList = newArr
      }).catch((err) => {
        this.materialList = []
      })
    },
    /* 选择退料原因 */
    changeReasonVal(val) {
      if (val == 6 && this.materialList && this.materialList.length > 0) {
        this.$refs.backDetail.handleAddList(this.materialList, 2);
      } else {
        this.$refs.backDetail.handleAddList([], 2);
      }
    },
    /* 选择退料物料 */
    changeMaterial(val) {
      let newArr = []
      let obj = {}
      if (!this.form.material) {
        return
      }
      const item = this.materialList.find(item => item.itemCode === val);
      console.info('item', item)
      obj = {
        "materialSerial": item.sequenceCode ? item.sequenceCode.split(',')[0] : '', //物料序列号
        "workorderCode": item.workorderCode, //工单编号
        "productCode": item.itemCode, //物料编码
        "productName": item.itemName, //物料名称
        "productSpec": item.specification, //规格型号
        "unitOfMeasure": item.unitOfMeasure, //单位
        "itemAmount": item.quantityIssued, //数量
        "snCode": null, //SN码
        "itemId": item.itemId, //物料id
        "maxCount": item.quantityIssued, //领料数量
        "warehouseId": item.warehouseId,
        "warehouseCode": item.warehouseCode,
        "warehouseName": item.warehouseName,
        "fmaterialType": item.jdySonType
      }
      console.log("++++++++++++", obj);
      this.form.material = null
      this.$refs.backDetail.handleAdd(obj, 2);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.addBackMaterialList = []
      this.$refs.backDetail.handleAddList([]);
    },
    /* 2024-11-21 原扫码方法 */
    /* querySnCodeInfo() {
        if (this.form.workorderCode && this.form.materialSerial) {
            this.parentCode = this.form.materialSerial;
            // let flag = false
            // this.snList.forEach(item => {
            //   if(item.issueCode === this.form.materialSerial){
            //     flag = true
            //   }
            // })
            // if(flag){
            //   this.form.materialSerial = this.selectSequenceCode
            // }
            const obj = {
                ...this.form
            }
            this.form.materialSerial = null
            this.$refs.backDetail.refreshBackList(obj);
        } else {
            this.$modal.msgError("请输入工单编号和序列号！！");
        }
    }, */
    /* 2024-11-21 扫码获取物料信息 */
    /*  querySnCodeInfo() {
         if (!this.form.workorderId || !this.form.materialSerial) {
             this.$modal.msgError("生产工单id、SN码不能为空！！");
         } else {
             let newArr = []
             let obj = {}
             let params = {
                 snCode: this.form.materialSerial,
                 workorderId: this.form.workorderId
             }
             getListByScanning(params).then((res) => {
                 obj = {
                     "materialSerial": res.data.materialSerial, //物料序列号
                     "workorderCode": res.data.workorderCode, //工单编号
                     "productCode": res.data.productCode, //物料编码
                     "productName": res.data.productName, //物料名称
                     "productSpec": res.data.productSpec, //规格型号
                     "unitOfMeasure": res.data.unitOfMeasure, //单位
                     "itemAmount": res.data.itemAmount, //数量
                     "snCode": res.data.snCode, //SN码
                     "maxCount": res.data.itemAmount, //领料数量
                 }
                 newArr.push(obj)
                 this.form.materialSerial = null
                 this.selectedRows = newArr
                 this.$refs.backDetail.handleAdd(obj, 1);
             }).catch(() => { })
         }
     }, */
    /* 2025-3-20  扫码获取物料信息 ,新增多sn同时获取物料信息*/
    querySnCodeInfo() {
      if (!this.form.workorderId || !this.form.materialSerial) {
        this.$modal.msgError("生产工单id、SN码不能为空！！");
      } else {

        // 空格（包括连续多个）和中文逗号，并将其替换为英文逗号
        let sn = this.form.materialSerial.trim().replace(/(\s+|，)/g, ',').replace(/,+$/, '');       // 剔除末尾的逗号
        this.form.materialSerial = sn
        let params = {
          snCodeList: this.form.materialSerial,
          workOrderId: this.form.workorderId
        }
        let newArr = []
        getListByScanning(params).then((res) => {
          if (res.data) {
            newArr = res.data.map(item => {
              return {
                "materialSerial": item.materialSerial, //物料序列号
                "workorderCode": item.workorderCode, //工单编号
                "productCode": item.productCode, //物料编码
                "productName": item.productName, //物料名称
                "productSpec": item.productSpec, //规格型号
                "unitOfMeasure": item.unitOfMeasure, //单位
                "itemAmount": item.itemAmount, //数量
                "snCode": item.snCode, //SN码
                "maxCount": item.itemAmount, //领料数量
              }
            })
          }
          this.form.materialSerial = null
          this.selectedRows = newArr
          this.$refs.backDetail.handleAddBatchList(newArr, 1);
        }).catch(() => { })
      }
    },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        backCode: null,
        backStatus: null,
        workorderCode: null,
        checkUser: null,
        checkTime: null,
        backUser: null,
        backTime: null,
        remark: null,
        materialSerial: null,
        processInstanceId: null,
        reasonVal: null,
        workorderId: null,
        material: null,
        backType: '1',
        warehouseId: null,
        warehouseCode: null,
        warehouseName: null,
        areaId: null,
        areaCode: null,
        areaName: null,
      };
      this.personList = [];
      this.activeStep = null;
      this.stepResult = null;
      this.resetForm("form");
      this.autoGenFlag = false;
      this.parentCode = "";
      this.optType = null;
      this.selectedRows = [];
      this.parentId = null;
      this.materialList = []
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加生产退料单";
      this.optType = "add";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      this.optType = "update";
      this.parentId = id;
      getBack(id).then(response => {
        this.form = response.data;
        // this.form.reasonVal = this.form.reasonVal);
        this.handleGetSN()
        this.open = true;
        this.title = "修改生产退料单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      console.info('this.form', this.form)
      if (this.selectedRows == null || this.selectedRows.size == 0) {
        this.$notify({
          title: "提示",
          type: "warning",
          message: "请至少选择一条数据!"
        });
        return;
      }
      /* 对退料数量进行限制 */
      for (let i in this.selectedRows) {
        console.info(this.selectedRows[i].maxCount, this.selectedRows[i].itemAmount)
        if (!this.selectedRows[i].itemAmount || this.selectedRows[i].itemAmount == 0) {
          this.$modal.msgError("退料数量不能为空或者0");
          return
        }
        if (this.selectedRows[i].itemAmount && this.selectedRows[i].itemAmount > this.selectedRows[i].maxCount) {
          this.$modal.msgError("退料数量不能超过领料数量");
          return
        }
      }
      const hasEmptyWarehouseCode = this.selectedRows.some(row => !row.warehouseCode);
      if (hasEmptyWarehouseCode) {
        this.$notify({
          title: "提示",
          type: "warning",
          message: "存在未选择仓库的物料明细,请检查!"
        });
        return false
      }
      console.info('this.selectedRows', this.selectedRows)
      this.$refs["form"].validate(valid => {
        if (valid) {
          let reqParam = {
            baseInfo: this.form,
            detailList: this.selectedRows
          };
          this.disabledSubmit = true
          if (this.form.id != null) {
            updateBatchBackInfo(reqParam).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.disabledSubmit = false
              this.getList();
            }).catch(() => {
              this.disabledSubmit = false
            });
          } else {
            addBatchBackInfo(reqParam).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.disabledSubmit = false
            }).catch(() => {
              this.disabledSubmit = false
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除生产退料单基础编号为"' + ids + '"的数据项？')
        .then(function () {
          return delBack(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /* 自动生成退货编码按钮  */
    handleAutoGenChange(autoGenFlag) {
      if (autoGenFlag) {
        genCode("MATERIAL_BACK").then(response => {
          this.form.backCode = response;
          this.$forceUpdate();
        });
      } else {
        this.form.backCode = null;
      }
    },
    //生成iqc质检单
    handleGenerate(row) {
      this.$modal
        .confirm('是否确认生产退料单基础编号为"' + row.backCode + '"的数据项生成质检单？')
        .then(function () {
          return backGenerate(row.id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("生成成功");
        }).catch(() => { });
      // backGenerate(row.id).then(res=>{
      //   console.log(res,'生成质检单的res');
      //   if(res.code == 200){
      //     this.$modal.msgSuccess("生成成功");
      //   }
      // })
    },
    // manage
    manageQuery(row, name, type) {
      selectUserRole(name).then((res) => {
        if (type == 'add') {
          this.handleAdd()
        } else if (type == 'edit') {
          this.handleUpdate(row)
        } else if (type == 'del') {
          this.handleDelete(row)
        } else if (type == 'quality') {
          this.handleGenerate(row)
        }

      }).catch(() => {
        //  this.$modal.msgError("此用户暂时没有权限");
        return "false"
      });
    },
  }
}
</script>
<style lang='scss' scoped>
.dialog-footer {
  padding-top: 20px;
  text-align: center;
}
</style>